package xyz.luan.audioplayers

import android.os.Handler
import io.flutter.plugin.common.MethodChannel
import java.lang.ref.WeakReference

internal class UpdateCallback constructor(
    mediaPlayers: MutableMap<String, Player>,
    channel: MethodChannel,
    handler: Handler,
    audioplayersPlugin: AudioplayersPlugin
) : Runnable {
    private val mediaPlayers: WeakReference<MutableMap<String, Player>> = WeakReference<MutableMap<String, Player>>(mediaPlayers)
    private val channel: WeakReference<MethodChannel> = WeakReference(channel)
    private val handler: WeakReference<Handler> = WeakReference(handler)
    private val audioplayersPlugin: WeakReference<AudioplayersPlugin> = WeakReference(audioplayersPlugin)
    override fun run() {
        val mediaPlayers: MutableMap<String, Player>? = mediaPlayers.get()
        val channel: MethodChannel? = channel.get()
        val handler: Handler? = handler.get()
        val audioplayersPlugin: AudioplayersPlugin? = audioplayersPlugin.get()
        if ((mediaPlayers == null) || (channel == null) || (handler == null) || (audioplayersPlugin == null)) {
            audioplayersPlugin?.stopPositionUpdates()
            return
        }
        var nonePlaying = true
        for (player: Player in mediaPlayers.values) {
            if (!player.isActuallyPlaying) {
                continue
            }
            try {
                nonePlaying = false
                val key: String? = player.playerId
                val duration: Int = player.duration
                val time: Int = player.currentPosition
                channel.invokeMethod(
                    "audio.onDuration",
                    AudioplayersPlugin.buildArguments(key, duration)
                )
                channel.invokeMethod(
                    "audio.onCurrentPosition",
                    AudioplayersPlugin.buildArguments(key, time)
                )
                if (audioplayersPlugin.seekFinish) {
                    channel.invokeMethod(
                        "audio.onSeekComplete",
                        AudioplayersPlugin.buildArguments(player.playerId, true)
                    )
                    audioplayersPlugin.seekFinish = false
                }
            } catch (e: UnsupportedOperationException) {
            }
        }
        if (nonePlaying) {
            audioplayersPlugin.stopPositionUpdates()
        } else {
            handler.postDelayed(this, 200)
        }
    }

}